<template>
    <div class="row">
        <div class="row" v-masonry transition-duration="0.3s" item-selector=".grid-item">
            <div class="col-md-3 grid-item text-center" v-for="(image, index) in imageList">
                <div class="ibox">
                    <div class="ibox-content product-box">
                        <div class="product-imitation material-news-body">
                            <!--图片素材-->
                            <div v-if="accept=='image' && image.view_url" class="product-imitation material-news-body">
                                <img class="img-responsive" v-show="image.view_url" :src="image.view_url+ '?imageView2/0/w/500/h/500'">
                            </div>
                            <div class="icon" v-if="accept == 'doc' && image.view_url">
                                <i class="fa fa-file"></i>
                            </div>
                            <div class="icon" v-if="accept == 'xls' && image.view_url">
                                <i class="fa fa-bar-chart-o"></i>
                            </div>
                            <div class="icon" v-if="accept == 'voice' && image.view_url">
                                <i class="fa fa-music"></i>
                            </div>
                            <div class="icon" v-if="accept == 'video' && image.view_url">
                                <i class="img-responsive fa fa-film"></i>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-9" style="padding-right: 0px;">
                                <input type="text" class="form-control" v-model="image.name" placeholder="请输入图片名称..." v-bind:disabled="disabled"/>
                            </div>
                            <div class="col-md-2" style="padding-left: 3px;" v-show="!disabled">
                                <button class="btn btn-warning btn-sm" type="button" v-on:click="trash(index)"><i class="fa fa-trash"></i></button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row" v-show="!disabled">
            <div class="col-md-10" :id="randomId"></div>
        </div>
    </div>
</template>
<script>
    //瀑布流
    import {VueMasonryPlugin} from 'vue-masonry';

    Vue.use(VueMasonryPlugin)
    /**
     * 使用方法
     * <webuploader-multiple :image-list.sync="autuReplyData.image_list" btn-text="选择相册"></webuploader-multiple>
     */
    //参考网址：http://www.mshady.com/archives/387
    export default {
        name: 'WebuploaderMutiple',
        props: {
            accept: {
                type: String,
                default: 'image',
            },
            imageList:{
                type: Array,
                default:function () {
                    return [];
                },
            },
            disabled:{
                type: Boolean,
                default:false,
            },
            btnText:{
                type: String,
                default:'上传',
            },
            // 上传地址
            uploaderUrl: {
                type: String,
                default: '/new/Admin/SysFile/webUpload',
            },
            staticPath: {
                type: String,
                default: '/vendor/webuploader/'
            },
            // 上传最大数量 默认为100
            fileNumLimit: {
                type: Number,
                default: 100,
            },
            // 大小限制 默认2M
            fileSingleSizeLimit: {
                type: Number,
                default: 1024 * 1024 * 50,
            },
            // 上传时传给后端的参数，一般为token，key等
            formData: {
                type: Object,
                default: null
            },
        },
        data() {
            return {
                randomId: 'webuploader_' + (Math.random() * 100000000000000000),
                scriptTagStatus: 0,
                uploader: null,
                loadBox: null,
                newImageList: _.cloneDeep(this.imageList),
            };
        },
        watch: {
            newImageList:function (val) {
                this.$emit('update:imageList', val);
            }
        },
        mounted() {
            this.initUploader();
        },
        created () {
            //瀑布流重新渲染
            this.$nextTick(function(){
                if (typeof this.$redrawVueMasonry === 'function') {
                    this.$redrawVueMasonry();
                }
            })
        },
        methods: {
            initUploader() {
                this.uploader = WebUploader.create({
                    auto: true, // 选完文件后，是否自动上传
                    swf: this.staticPath + 'Uploader.swf',  // swf文件路径
                    server: this.uploaderUrl,  // 文件接收服务端
                    pick: {
                        id: '#' + this.randomId,     // 选择文件的按钮
                        name: "file",
                        multiple: true,   // 是否多文件上传 默认false
                        label: this.btnText,
                    },
                    accept: this.getAccept(this.accept),  // 允许选择文件格式。
                    fileNumLimit: this.fileNumLimit, // 限制上传个数
                    //fileSingleSizeLimit: this.fileSingleSizeLimit, // 限制单个上传图片的大小
                    formData: this.formData,  // 上传所需参数
                    //设置文件上传域的name
                    fileVal: 'file',
                    duplicate: true,//是否可重复选择同一文件
                    resize: false,
                    compress: null,//图片不压缩
                    chunked: true,//分片处理
                    fileSingleSizeLimit: 1024 * 1024 * 50,//验证单个文件大小是否超出限制,50M
                    chunkSize: 1 * 1000 * 1000, //每片1M
                    chunkRetry: 2,//如果失败，重试2次
                    threads: 1,//上传并发数。允许同时最大上传进程数。
                    runtimeOrder: 'flash,html5',
                    // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
                    disableGlobalDnd: true
                });
                this.uploader.on('uploadBeforeSend', (block, data, headers) => {
                    data.fileType = this.accept;
                    //头部成熟
                    let token = document.head.querySelector('meta[name="csrf-token"]');
                    headers['X-CSRF-TOKEN'] = token.content;
                });
                // 当有文件被添加进队列的时候，添加到页面预览
                this.uploader.on('fileQueued', (file) => {
                    this.$emit('fileChange', file);
                });

                this.uploader.on('uploadStart', (file) => {
                    // 在这里可以准备好formData的数据
                    //this.uploader.options.formData.key = this.keyGenerator(file);
                });

                // 文件上传过程中创建进度条实时显示。
                this.uploader.on('uploadProgress', (file, percentage) => {
                    this.loadBox = layer.load(1, {
                        shade: [0.3, '#fff'] //0.1透明度的白色背景
                    });
                    this.$emit('progress', file, percentage);
                });

                this.uploader.on('uploadSuccess', (file, response) => {
                    if (response.status == 'success' && _.isEmpty(response.data) == false){
                        this.newImageList.push(response.data);
                    }else{
                        utils.showToastr({'status':'error','title':'上传失败','message':response.data.msg});
                    }
                    this.$emit('success', file, response);
                });

                this.uploader.on('uploadError', (file, reason) => {
                    console.error(reason);
                    this.$emit('uploadError', file, reason);
                });

                this.uploader.on('error', (type) => {
                    let errorMessage = '';
                    if (type === 'F_EXCEED_SIZE') {
                        errorMessage = `文件大小不能超过${this.fileSingleSizeLimit / (1024 * 1000)}M`;
                    } else if (type === 'Q_EXCEED_NUM_LIMIT') {
                        errorMessage = '文件上传已达到最大上限数';
                    } else {
                        errorMessage = `上传出错！请检查后重新上传！错误代码${type}`;
                    }
                    this.$emit('error', errorMessage);
                });

                this.uploader.on('uploadComplete', (file, response) => {
                    layer.close(this.loadBox);
                    this.$emit('complete', file, response);
                });
            },
            getAccept(accept) {
                switch (accept) {
                    case 'doc':
                        return {
                            title: 'Docs',
                            extensions: 'doc,docx,ppt,pptx,pdf,txt',
                            mimeTypes: '.doc,docx,.ppt,.pptx,.pdf,.txt'
                        };
                        break;
                    case 'xls':
                        return {
                            title: 'Xls',
                            extensions: 'xls,xlsx',
                            mimeTypes: '.xls,.xlsx'
                        };
                        break;
                    case 'video':
                        return {
                            title: '视频文件',
                            extensions: 'mp4,flv,mkv,wmv',
                            mimeTypes: "video/*",
                        };
                        break;
                    case 'voice':
                        return {
                            title: '语音文件',
                            extensions: 'mp3,wma,wav,amr',
                            mimeTypes: 'audio/*'
                        };
                        break;
                    case 'image':
                        return {
                            title: 'Images',
                            extensions: 'gif,jpg,jpeg,bmp,png',
                            mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png'
                        };
                        break;
                    default:
                        return accept
                }
            },
            refresh(){
                this.uploader.refresh();
            },
            trash:function (index) {
                layer.confirm('你确定删除该图片么？', {icon: 3, title: '删除提示',shadeClose: true,}, (boxIndex) => {
                    this.imageList.splice(index, 1);
                    layer.close(boxIndex);
                    //瀑布流重新渲染
                    this.$nextTick(function(){
                        if (typeof this.$redrawVueMasonry === 'function') {
                            this.$redrawVueMasonry();
                        }
                    })
                });
            }
        },
    };
</script>
<style lang="scss">
    .webuploader-container {
        position: relative;
    }
    .webuploader-element-invisible {
        position: absolute !important;
        clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
        clip: rect(1px,1px,1px,1px);
    }
    .webuploader-pick {
        position: relative;
        display: inline-block;
        cursor: pointer;
        background: #00b7ee;
        padding: 10px 15px;
        color: #fff;
        text-align: center;
        border-radius: 3px;
        overflow: hidden;
    }
    .webuploader-pick-hover {
        background: #00a2d4;
    }

    .webuploader-pick-disable {
        opacity: 0.6;
        pointer-events:none;
    }
    .webuploader-pick{
        width: 120px;
        height: 40px;
    }
    .material-news-body {
        /*border: 1px solid rgb(231, 231, 235);*/
        text-align: left;
        color: rgb(34, 34, 34);
        padding: 10px;
        /*margin: 0px 10px 0px 0px;*/
        background-color:#FFFFFF;
    }
</style>